package com.springInit;


import com.mvc.annotion.*;
import com.mvc.pojo.Handler;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *  zj：web.xml->sacepackge->缓存class path->反射为 obj
 *          ->遍历obj field.isAnnotation 注入属性赋值 doAutoWired
 *            -> 事务注解 @Transactional  通过字节数组生成 proxy obj __invoke real obj
 *              -> 缓存map 映射__ handlerMapping |Handler(url-obj-method-paramIndexMapping)
 *                // HandlerAdapter -多类型参数动态匹配
 *              method.invoke(Object obj, Object... args 数组入参)
 *       getClass().getDeclaredFields()、getClass().getDeclaredMethods()
 *       getClass().getClassLoader()、getClass().getMethods()、getClass().isAnnotationPresent
 *
 *   ###类加载器的强大之处——InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(String)
 *   ###  URL resourcePath = this.getClass().getClassLoader().getResource("/" + urlpackage)
 *        Class<?> clazz = Class.forName(className)、Object instance = clazz.newInstance()、field.isAnnotationPresent(Resource.class)
 *        properties.load(InputStream ..)、String className = (scanPackage + "." + file.getName().replace(".class",""))、
 *        Service myService = clazz.getAnnotation(Service.class)、Field[] fields = instrance.getClass().getDeclaredFields()
 *        baseUrl = instrance.getClass().getAnnotation(RequestMapping.class).value()
 *        String mappingUrl = method.getAnnotation(RequestMapping.class).value()
 */
public class DispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();
    //缓存class路径-
    List<String> classNameList = new ArrayList<String>();
    //所有的controller和service的路径和实例化对象
    Map<String, Object> iocMap = new HashMap<String, Object>();
    //所有的controller下的方法路径和方法method对象的映射关系
    Map<String, Method> methodMapping = new HashMap<String, Method>();

    // 存储url和Method之间的映射关系
    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    public void init(ServletConfig config) {
        // 1 加载配置文件：类路径 class: springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        //文件-》对象赋值-
        doLoadConfig(contextConfigLocation);
        //1.包扫描 -》类路径 class
        sacepackge(properties.getProperty("scanPackage"));
        //2.反射-> 实例化
        instranceClass();
        //3.依赖注入
        doAutoWired();
        //处理普通对象转换为代理对象。
        doProxy();
        //代理对象二次注入
        reginAuto();
        //4.方法的映射
        mappingMethod();

        System.out.println("容器初始化完成 ....ok");
    }

    /**
     * 针对处理完毕的对象，二次依赖注入...
     */
    private void reginAuto() {
        for (Map.Entry<String, Object> entry : iocMap.entrySet()) {
            Class clazz = entry.getValue().getClass();
            if (clazz.isAnnotationPresent(Controller.class)) {
                Field[] fields = entry.getValue().getClass().getDeclaredFields();
                for (Field field : fields) {
                    if (!field.isAnnotationPresent(Resource.class)) {
                        continue;
                    }
                    Resource myAutowired = field.getAnnotation(Resource.class);
                    String beanName = myAutowired.value().trim();
                    // 获取 myAutowired 注解的值
                    if ("".equals(beanName)) {
                        System.out.println("[INFO] myAutowired.value() is null");
                        beanName = field.getType().getName();
                    }
                    // 只要加了注解，都要加载，不管是 private 还是 protect
                    field.setAccessible(true);
                    try {
                        field.set(entry.getValue(), iocMap.get(beanName));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    //代理对象包装
    private void doProxy() {
        //beanName ---> instance
        if (iocMap.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : iocMap.entrySet()) {
            //对象->类中的方法-->方法上的注解
            Method[] methods = entry.getValue().getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(Transactional.class)) {
                    //替换普通对象为代理对象-
                    Object instance=entry.getValue();
                    CglibProxy cglib = new CglibProxy();//实例化CglibProxy对象
                    instance=cglib.getCglibProxy(instance);//获取代理对象
                    //覆盖为代理对象
                    iocMap.put(entry.getKey(),instance);
                }
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");
        try {
            Handler handler=getHandler(req);
            if (handler == null) {
                resp.getWriter().write("404 not found");
                return;
            }
            // 参数绑定
            // 获取所有参数类型数组，这个数组的长度就是我们最后要传入的args数组的长度
            Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
            // 根据上述数组长度创建一个新的数组（参数数组，是要传入反射调用的）
            Object[] paraValues = new Object[parameterTypes.length];
            // 以下就是为了向参数数组中塞值，而且还得保证参数的顺序和方法中形参顺序一致
            Map<String, String[]> parameterMap = req.getParameterMap();
            // 遍历request中所有参数  （填充除了request，response之外的参数）
            for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
                // name=1&name=2   name [1,2]
                String value =param.getValue()[0];  // 如同 1,2
                String key="";
                if(param.getKey() instanceof String){
                    key="String";
                }
                // 如果参数和方法中的参数匹配上了，填充数据
                if (!handler.getParamIndexMapping().containsKey(key)) {
                    continue;
                }
                // 方法形参确实有该参数，找到它的索引位置，对应的把参数值放入paraValues
                Integer index = handler.getParamIndexMapping().get(key);//name在第 2 个位置
                paraValues[index] = value;  // 把前台传递过来的参数值填充到对应的位置去
            }
            int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName()); // 0
            paraValues[requestIndex] = req;
            int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName()); // 1
            paraValues[responseIndex] = resp;
            // end-
            String resMsg= (String) handler.getMethod().invoke(handler.getController(), paraValues);

            PrintWriter writer = resp.getWriter();
            writer.println(resMsg);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取处理器-
     * @param req
     * @return
     */
    private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) {
            return null;
        }
        String url = req.getRequestURI();

        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }
        return null;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        this.doPost(req,resp);
    }

    // 加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //url --object 映射保存
    private void mappingMethod() {
        for (Map.Entry entry : iocMap.entrySet()) {
            Object instrance = entry.getValue();
            //缓存-处理controller
            if(!instrance.getClass().isAnnotationPresent(Controller.class)){
                continue;
            }
            String baseUrl = "";
            baseUrl = instrance.getClass().getAnnotation(RequestMapping.class).value();
            Method[] methods = instrance.getClass().getMethods();
            //取类下边的方法-controller中的方法
            for (Method method : methods) {
                if(method.isAnnotationPresent(RequestMapping.class)){
                    String mappingUrl = method.getAnnotation(RequestMapping.class).value();

                    methodMapping.put(baseUrl + mappingUrl, method);
                    Handler handler = new Handler(instrance, method, Pattern.compile(baseUrl + mappingUrl));
                    //处理参数绑定-
                    // 计算方法的参数位置信息  // query(HttpServletRequest request, HttpServletResponse response,String name)
                    Parameter[] parameters = method.getParameters();
                    for (int j = 0; j < parameters.length; j++) {
                        Parameter parameter = parameters[j];

                        if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                            // 如果是request和response对象，那么参数名称写HttpServletRequest和HttpServletResponse
                            handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), j);
                        } else {
                            handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), j);  // <name,2>
                        }
                    }
                    handlerMapping.add(handler);
                }
            }
        }
    }
    // 对 Resource字段注入
    private void doAutoWired() {
        for (Map.Entry entry : iocMap.entrySet()) {
           Object instrance = entry.getValue();
            //所有bean 遍历 -进行依赖注入，
            Field[] fields = instrance.getClass().getDeclaredFields();
            //多个字段-
            for (Field field : fields) {
                if (field.isAnnotationPresent(Resource.class)) {
                    try {
                        //允许赋值
                        field.setAccessible(true);
                        field.set(instrance, iocMap.get(field.getName()));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
       }
    }

    /**
     * 基于classNames缓存的类的全限定类名，以及反射技术，完成对象创建和管理
     */
    private void instranceClass() {
        if (classNameList.size() <= 0) {
            return;
        }
        try {
            for (String className : classNameList) {
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(Controller.class)) {
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    Object instance = clazz.newInstance();
                    // 保存在 ioc 容器
                    iocMap.put(beanName, instance);
                } else if (clazz.isAnnotationPresent(Service.class)) {
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    // 如果注解包含自定义名称
                    Service myService = clazz.getAnnotation(Service.class);
                    if (!"".equals(myService.value())) {
                        beanName = myService.value();
                    }
                    Object instance = clazz.newInstance();
                    iocMap.put(beanName, instance);
                    // 找类的接口
                    for (Class<?> i : clazz.getInterfaces()) {
                        if (iocMap.containsKey(i.getName())) {
                            throw new Exception("The Bean Name Is Exist.");
                        }
                        iocMap.put(i.getName(), instance);
                    }
                } else if (clazz.isAnnotationPresent(Dao.class)) {
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    // 如果注解包含自定义名称
                    Dao myDao = clazz.getAnnotation(Dao.class);
                    if (!"".equals(myDao.value())) {
                        beanName = myDao.value();
                    }
                    Object instance = clazz.newInstance();
                    iocMap.put(beanName, instance);
                    // 找类的接口
                    for (Class<?> i : clazz.getInterfaces()) {
                        if (iocMap.containsKey(i.getName())) {
                            throw new Exception("The Bean Name Is Exist.");
                        }
                        iocMap.put(i.getName(), instance);
                    }
                } else if (clazz.isAnnotationPresent(Component.class)) {
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    Object instance = clazz.newInstance();
                    // 如果注解包含自定义名称
                    Component myComponent = clazz.getAnnotation(Component.class);
                    if (!"".equals(myComponent.value())) {
                        beanName = myComponent.value();
                    }
                    // 保存在 ioc 容器
                    iocMap.put(beanName, instance);
                    // 找类的接口
                    for (Class<?> i : clazz.getInterfaces()) {
                        if (iocMap.containsKey(i.getName())) {
                            throw new Exception("The Bean Name Is Exist.");
                        }
                        iocMap.put(i.getName(), instance);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 参数转换，，
     *
     * @param className
     * @return
     */
    private String toLowerFirstCase(String className) {
        char[] charArray = className.toCharArray();
        charArray[0] += 32;
        return String.valueOf(charArray);
    }

    /**
     * 扫描 磁盘class
     *
     */
    private void sacepackge(String scanPackage) {
        String urlpackage = scanPackage.replaceAll("\\.", "/");

        URL resourcePath = this.getClass().getClassLoader().getResource("/" + urlpackage);

        if (resourcePath == null) {
            return;
        }

        File classPath = new File(resourcePath.getFile());

        for (File file : classPath.listFiles()) {

            if (file.isDirectory()) {

                System.out.println("[INFO-2] {" + file.getName() + "} is a directory.");

                // 子目录递归
                sacepackge(scanPackage + "." + file.getName());

            } else {

                if (!file.getName().endsWith(".class")) {
                    System.out.println("[INFO-2] {" + file.getName() + "} is not a class file.");
                    continue;
                }

                String className = (scanPackage + "." + file.getName().replace(".class",""));

                // 保存在内容
                classNameList.add(className);

                System.out.println("[INFO-2] {" + className + "} has been saved in classNameList.");
            }
        }

    }


}
